package sncf;


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


public class ChoixJour extends JPanel implements DocumentListener{

	private static final long serialVersionUID = 1L;
	private JLabel jl1;
	private JTextField jt2;
	private JButton jb1;
	private JButton jb2;
	static final SimpleDateFormat myFmt = new SimpleDateFormat("dd/MM/yyyy");;
	
	public ChoixJour(Controler ctr){
		super();
		this.setLayout(new GridLayout(4,1));
		
		jb1 = new JButton("Aujourd'hui");
		jb2 = new JButton("Demain");
		jl1 = new JLabel("Vous partez:");
		jt2 = new JTextField();
		
		this.add(jl1);
		this.add(jt2);
		this.add(jb1);
		this.add(jb2);
		
		jt2.getDocument().addDocumentListener(this);
		
		jb1.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Date date = new Date();
				
				jt2.setText(myFmt.format(date));
				
			}
			
		});
		jb2.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				Date date = new Date();
				
				long myTime=(date.getTime()/1000)+60*60*24;
				date.setTime(myTime*1000);
				
				jt2.setText(myFmt.format(date));
				
			}
			
		});	
		
	}
	
	public Date getJour() throws ParseException{
		String sjour = jt2.getText();
		if (isDate(sjour)){
		Date date = myFmt.parse(sjour);
		return date;	
		} else {
			return null;
		}
	}



	@Override
	public void changedUpdate(DocumentEvent e) {
		update(e);
		
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		update(e);
		
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		update(e);
		
	}
	
	public void update(DocumentEvent e){
		String text = jt2.getText();
		if (isDate(text)){
			jt2.setBackground(new Color(200, 255, 255));
		} else {
			jt2.setBackground(new Color(255, 200, 200));
		}
		
	}

	private boolean isDate(String text) {
		String regex = "[0-9]{2}/[0-9]{2}/[0-9]{4}";// Regulate Expression
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(text);
		return matcher.matches();		
	}



}
